package com.lovemanai.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 设置字符编码
 * 验证用户是否登录，否则跳转到登录界面
 * @author lovemanai
 *
 */
@WebFilter(filterName = "authority", urlPatterns = "/*",
		initParams = {
		@WebInitParam(name = "encoding", value = "utf-8"),
		@WebInitParam(name = "loginPage", value = "/login.jsp"),
		@WebInitParam(name = "welcomePage", value = "/welcome.jsp")
})
public class AuthorityFilter implements Filter {

	private FilterConfig config;
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}
	
	@Override
	public void destroy() {
		this.config = null;
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//获取参数
		String encoding = config.getInitParameter("encoding");
		String loginPage = config.getInitParameter("loginPage");
		String welcomePage = config.getInitParameter("welcomePage");
		
		//获得Session
		HttpServletRequest hrequest = (HttpServletRequest)request;
		HttpSession session = hrequest.getSession();
		
		//获得用户请求地址
		String requestPath = hrequest.getServletPath();
		//设置字符编码
		response.setCharacterEncoding(encoding);
		
		
		if(session.getAttribute("username") != null && requestPath.endsWith(loginPage)) {
			chain.doFilter(request, response);
		} else {
			request.setAttribute("tip", "您还没有登录");
			request.getRequestDispatcher(loginPage).forward(request, response);
		}
	}



}
